import 'dart:io';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

import 'app_video_controls.dart';

//app视频播放器
class AppVideoPlayer extends StatefulWidget {
  const AppVideoPlayer({
    super.key,
    this.url,
    this.filePath,
    this.title,
    this.aspectRatio = 1.77,
    this.autoPlay = false,
    this.looping = false,
    this.onCreated,
  });

  final String? url;
  final String? filePath;
  final String? title;
  final double aspectRatio; //播放器比例
  final bool autoPlay;
  final bool looping;
  final Function(ChewieController controller)? onCreated;

  @override
  State<AppVideoPlayer> createState() => _AppVideoPlayerState();
}

class _AppVideoPlayerState extends State<AppVideoPlayer> {
  late ChewieController _chewieController;
  late VideoPlayerController _playerController;

  @override
  initState() {
    initController();
    super.initState();
  }

  initController() async {
    if (widget.url != null) {
      _playerController =
          VideoPlayerController.networkUrl(Uri.parse(widget.url!));
    } else if (widget.filePath != null) {
      _playerController = VideoPlayerController.file(File(widget.filePath!));
    }

    _chewieController = ChewieController(
      videoPlayerController: _playerController,
      aspectRatio: widget.aspectRatio,
      autoPlay: widget.autoPlay,
      looping: widget.looping,
      showOptions: false,
      customControls: const AppVideoControls(),
      allowMuting: false,
      materialProgressColors: ChewieProgressColors(
        backgroundColor: const Color(0xFF4B494A),
        handleColor: Colors.white,
        playedColor: Colors.white,
        bufferedColor: Colors.grey.withOpacity(0.5),
      ),
    );

    try {
      await _playerController.initialize();
    } catch (error) {
      return;
    }

    widget.onCreated?.call(_chewieController);
  }

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
        aspectRatio: widget.aspectRatio,
        child: Chewie(controller: _chewieController)); //视频
  }

  @override
  void dispose() {
    _chewieController.dispose();
    super.dispose();
  }
}
